<?php

namespace app\common;

use support\Response;

class View
{
    /**
     * 视图 function
     *
     * @param string $template
     * @param array $vars
     * @param string|null $app
     * @param string|null $plugin
     * @return Response
     */
    public static function fetch(
        string $template = "",
        array $vars = [],
        string $app = null,
        string $plugin = null
    ): Response {
        if ($template == "") {
            $action = request()->action;
            $controller = new \ReflectionClass(request()->controller);
            $controller = str_replace(config('app.controller_suffix', ''), "", $controller->getShortName());
            $controller = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $controller));
            $template = "$controller/$action";
        }
        return view(template: $template, vars: $vars, app: $app, plugin: $plugin);
    }

    /**
     * assign function
     *
     * @param array|string $name
     * @param mixed $value
     * @return void
     */
    public static function assign(array|string $name, mixed $value = null)
    {
        $request = \request();
        $plugin = $request->plugin ?? '';
        $handler = \config($plugin ? "plugin.$plugin.view.handler" : 'view.handler');
        $handler::assign($name, $value);
    }
}
